package com.bigger.arch.app.service.controller;

import com.bigger.arch.app.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationListener;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

@RestController
@RequestMapping("/hello")
public class HelloController implements ApplicationListener<WebServerInitializedEvent> {

    private int port;

    private int getPort() {
        return port;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.port = event.getWebServer().getPort();
    }

    public String getHostName() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
            return address.getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Autowired
    private DiscoveryClient client;

    @RequestMapping("/sayHello")
    public String sayHello(@RequestParam String name) {

        List<ServiceInstance> instances = client.getInstances("bigger-app-service");
        if (!ObjectUtils.isEmpty(instances)) {
            ServiceInstance serviceInstance = instances.get(0);

            //return "Host: " + serviceInstance.getHost() + "Port:" + serviceInstance.getPort() + " " + "ServiceID:" + serviceInstance.getServiceId() + " sayHello:Hello " + name;
            return "Host: " + getHostName() + " Port:" + getPort() + " ServiceID:" + serviceInstance.getServiceId() + " sayHello:Hello " + name;
        }
        return "Host: " + getHostName() + " Port:" + getPort() + " sayHello:Hello " + name;
    }

    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    public UserDto saveUser(@RequestBody @Valid UserDto userDto, Errors errors) {

        //@RequestBody说明接口的contentType 是以application-json请求的


        if (errors.hasErrors()) {
            return null;
        }
        return userDto;
    }

}
